package com.battle.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.battle.pojo.entity.*;
import com.battle.pojo.param.trainingUser.*;
import com.battle.pojo.param.trainingUserDetails.CreateTrainingUserDetailsParam;
import com.battle.pojo.vo.trainingUser.*;
import com.battle.pojo.dto.trainingUser.*;
import com.battle.service.repository.in.*;
import com.battle.service.service.in.TrainingUserService;
import nirvana.core.domains.vo.PageResult;
import nirvana.core.exceptions.BizException;
import nirvana.core.utils.ids.IdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【描 述】：我的训练记录服务
 * 【环 境】：J2SE 17
 * 【详 细】：
 */
@Service
public class TrainingUserServiceImpl implements TrainingUserService {

    private final TrainingUserRepository trainingUserRepository;
    private final TrainingUserDetailsRepository userDetailsRepository;
    private final PersonWarCaseRepository personWarCaseRepository;
    private final UserRepository userRepository;
    private final TrainingProgramRepository programRepository;

    public TrainingUserServiceImpl(TrainingUserRepository trainingUserRepository, TrainingUserDetailsRepository userDetailsRepository, PersonWarCaseRepository personWarCaseRepository, UserRepository userRepository, TrainingProgramRepository programRepository) {
        this.trainingUserRepository = trainingUserRepository;
        this.userDetailsRepository = userDetailsRepository;
        this.personWarCaseRepository = personWarCaseRepository;
        this.userRepository = userRepository;
        this.programRepository = programRepository;
    }


    /**
     * 创建我的训练记录
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createTrainingUser(CreateTrainingUserParam param) {
        TrainingUser trainingUser = new TrainingUser();
        BeanUtils.copyProperties(param, trainingUser);
        Long id = IdGenerator.SNOW.generate();
        trainingUser.setId(id);

        //根据人员id拿到组织架构id和path
        List<Long> organizationIds = new ArrayList<>();
        //todo 根据当前人员查出多个组织架构id
        String organizationId = JSONArray.toJSONString(organizationIds);
        trainingUser.setDepartmentId(organizationId);

        //训练项目
        saveUserDetails(param.getTrainingUserDetailsList(), trainingUser, id);

        if (!trainingUserRepository.create(trainingUser)) {
            throw new BizException("创建我的训练记录失败");
        }
    }

    void saveUserDetails(List<CreateTrainingUserDetailsParam> params, TrainingUser trainingUser, Long id) {
        //根据id查找
        List<TrainingUserDetails> deleteList = getUserDetailsByUserDetailsId(id);
        if (CollectionUtil.isNotEmpty(deleteList)) {
            List<Long> ids = deleteList.stream().map(TrainingUserDetails::getId).distinct().collect(Collectors.toList());
            if (!userDetailsRepository.trueDeletionByIds(ids)) {
                throw new BizException("删除我的训练记录详情失败");
            }
        }
        List<TrainingUserDetails> trainingUserDetailsList = new ArrayList<>();

        //训练项目详情
        for (CreateTrainingUserDetailsParam detailsParam : params) {
            TrainingUserDetails details = new TrainingUserDetails();
            BeanUtils.copyProperties(trainingUser, details);
            BeanUtils.copyProperties(detailsParam, details);
            details.setId(IdGenerator.SNOW.generate());
            details.setTrainingUserId(id);

            //查询项目信息
            TrainingProgram program = programRepository.getByIdCheck(detailsParam.getTrainingProgramId());
            details.setUnit(program.getUnit());
            details.setType(program.getType());
            trainingUserDetailsList.add(details);
        }
        if (!userDetailsRepository.saveBatch(trainingUserDetailsList)) {
            throw new BizException("创建我的训练记录详情失败");
        }
    }

    List<TrainingUserDetails> getUserDetailsByUserDetailsId(Long id) {
        TrainingUserDetails details = new TrainingUserDetails();
        details.setTrainingUserId(id);
        return userDetailsRepository.getListByEntity(details);
    }

    /**
     * 修改我的训练记录
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editTrainingUser(EditTrainingUserParam param) {
        Long id = param.getId();
        TrainingUser trainingUser = trainingUserRepository.getByIdCheck(id);
        BeanUtils.copyProperties(param, trainingUser);

        //训练项目
        saveUserDetails(param.getTrainingUserDetailsList(), trainingUser, id);

        if (!trainingUserRepository.edit(trainingUser)) {
            throw new BizException("创建我的训练记录失败");
        }
    }

    /**
     * 移除我的训练记录
     *
     * @param id
     */
    @Override
    public void removeTrainingUser(Long id) {
        trainingUserRepository.removeById(id);
    }

    /**
     * 启动/禁用我的训练记录
     *
     * @param id
     */
    @Override
    public void enabledTrainingUser(Long id) {
        TrainingUser trainingUser = trainingUserRepository.getByIdCheck(id);
        trainingUser.setIsDisable(!trainingUser.getIsDisable());
        trainingUserRepository.edit(trainingUser);
    }

    /**
     * 获取我的训练记录详情
     *
     * @param id
     * @return
     */
    @Override
    public GetTrainingUserVo getTrainingUser(Long id) {
        TrainingUser trainingUser = trainingUserRepository.getByIdCheck(id);
        GetTrainingUserVo vo = new GetTrainingUserVo();
        BeanUtils.copyProperties(trainingUser, vo);

        List<CreateTrainingUserDetailsParam> params = new ArrayList<>();
        //项目
        List<TrainingUserDetails> trainingUserDetailsList = getUserDetailsByUserDetailsId(id);
        if (CollectionUtil.isNotEmpty(trainingUserDetailsList)) {
            for (TrainingUserDetails details : trainingUserDetailsList) {
                CreateTrainingUserDetailsParam param = new CreateTrainingUserDetailsParam();
                BeanUtils.copyProperties(details, param);
                //查询项目信息
                TrainingProgram program = programRepository.getByIdCheck(details.getTrainingProgramId());
                param.setTrainingProgramName(program.getName());
                params.add(param);
            }
        }
        vo.setTrainingUserDetailsList(params);

        //编辑用户名称
        User user = userRepository.getById(trainingUser.getUpdater());
        if (user != null) {
            vo.setUpdateUserName(user.getName());
        }

        return vo;
    }

    /**
     * 获取我的训练记录 列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<GetTrainingUserListVo> getTrainingUserList(GetTrainingUserListParam param) {

        SelectTrainingUserDto dto = new SelectTrainingUserDto();
        BeanUtils.copyProperties(param, dto);
        Page<GetTrainingUserListVo> page = trainingUserRepository.selectTrainingUser(dto);
        List<GetTrainingUserListVo> list = page.getRecords();

        if (CollectionUtil.isNotEmpty(list)) {
            List<Long> userIds = new ArrayList<>();
            list.forEach(v -> {
                userIds.add(v.getUserId());
            });
            Map<Long, User> userMap = userRepository.getMap(userIds);

            if (CollectionUtil.isNotEmpty(userMap)) {
                for (GetTrainingUserListVo vo : list) {
                    User user = userMap.get(vo.getUpdater());
                    if (user != null) {
                        vo.setUpdateUserName(user.getName());
                    }
                }
            }
        }
        return new PageResult<>(list, page);

    }

    /**
     * 获取我的训练记录下拉列表
     *
     * @param param
     * @return
     */
    @Override
    public List<GetTrainingUserDownListVo> getTrainingUserDownList(GetTrainingUserDownListParam param) {
        TrainingUser po = new TrainingUser();
        if (param != null) {
            BeanUtils.copyProperties(param, po);
        }
        List<TrainingUser> trainingUserList = trainingUserRepository.getListByEntity(po);

        List<GetTrainingUserDownListVo> list = new ArrayList<>();
        for (TrainingUser trainingUser : trainingUserList) {
            GetTrainingUserDownListVo vo = new GetTrainingUserDownListVo();
            BeanUtils.copyProperties(trainingUser, vo);
            list.add(vo);
        }
        return list;
    }


}



